package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.Subject.OneSubject;
import com.atguigu.eduservice.entity.Subject.TwoSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ms
 * @since 2022-05-19
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询所有的一级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", "0");
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapper);

        //查询所有的二级分类
        wrapper = new QueryWrapper<>();
        wrapper.ne("parent_id", "0");
        List<EduSubject> twoSubjects = baseMapper.selectList(wrapper);

        //分装一级分类
        List<OneSubject> finalSubjects = new ArrayList<>();
        for (EduSubject oneSubject : oneSubjects) {
            OneSubject one = new OneSubject();
            one.setId(oneSubject.getId());
            one.setTitle(oneSubject.getTitle());
            finalSubjects.add(one);
            //分装二级分类
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (EduSubject twoSubject : twoSubjects) {
                if (twoSubject.getParentId().equals(oneSubject.getId())) {
                    twoSubjectList.add(new TwoSubject(twoSubject.getId(), twoSubject.getTitle()));
                }
            }
            one.setChildren(twoSubjectList);
        }
        return finalSubjects;
    }


}
